﻿using AntUnion.FrameWork.Model.Models;
using AntUnion.FrameWork.Util;
using AntUnion.FrameWork.Web.Common;
using AntUnion.FrameWork.Web.Extend;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;

namespace AntUnion.FrameWork.Web.Service
{
    /// <summary>
    /// 公共配置项服务类
    /// </summary>
    public class PublicService
    {
        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="Mail"></param>
        /// <returns></returns>
        public bool IsValidEmail(string mail)
        {
            string strRegex = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(strRegex);
            if (re.IsMatch(mail))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 验证手机
        /// </summary>
        /// <param name="Mail"></param>
        /// <returns></returns>
        public bool IsValidPhone(string phone)
        {
            string strRegex = @"^1(3[0-9]|5[0-9]|7[6-8]|8[0-9])[0-9]{8}$";
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(strRegex);
            if (re.IsMatch(phone))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="Mail"></param>
        /// <returns></returns>
        public bool IsValidPassword(string passowrd)
        {
            string strRegex = @"^(?:(?=.*[0-9].*)(?=.*[A-Za-z].*)).{6,}";
            System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(strRegex);
            if (re.IsMatch(passowrd))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 生成短信验证码
        /// </summary>
        /// <returns></returns>
        private static string VerifyCode()
        {
            Random random = new Random();
            return random.Next(100000, 999999).ToString();
        }

        /// <summary>
        /// 隐藏邮箱
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static string HideEmail(string email)
        {
            int atIndex = email.IndexOf("@");
            string prefix = email.Substring(0, 3) + "*****";
            string suffix = email.Substring(atIndex);
            return prefix + suffix;
        }

        #region 缓存

        private static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());

        /// <summary>
        /// 验证缓存项是否存在
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public bool ExistsCache(string key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            return Cache.TryGetValue(key, out _);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <param name="value">缓存Value</param>
        /// <param name="expiresIn">缓存时长</param>
        /// <param name="isSliding">是否滑动过期（如果在过期时间内有操作，则以当前时间点延长过期时间）</param>
        /// <returns></returns>
        public bool SetCache(string key, object value, TimeSpan expiresIn, bool isSliding = false)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            Cache.Set(key, value,
                isSliding
                    ? new MemoryCacheEntryOptions().SetSlidingExpiration(expiresIn)
                    : new MemoryCacheEntryOptions().SetAbsoluteExpiration(expiresIn));

            return ExistsCache(key);
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public void RemoveCache(string key)
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            Cache.Remove(key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public T GetCache<T>(string key) where T : class
        {
            if (key == null)
                throw new ArgumentNullException(nameof(key));

            return Cache.Get(key) as T;
        }

        #endregion

        #region 获取码表

        public class CodeModel
        {
            public int id { get; set; }
            public string type { get; set; }
            public string typeName { get; set; }
            public string names { get; set; }
            public int code { get; set; }
            public string remark { get; set; }
            public string creator { get; set; }
            public DateTime createDate { get; set; }
            public int sort { get; set; }
        }

        /// <summary>
        /// 通过类型获取码表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<CodeModel> GetCode(string type)
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = from n in mtContext.TbCodes.AsNoTracking().Where(k => k.CoType == type && k.Status == 0)
                               join c in mtContext.TbCodetypes.AsNoTracking()
                               on n.CoType equals c.CtCode
                               select new CodeModel
                               {
                                   id = n.CoId,
                                   type = c.CtCode,
                                   typeName = c.CtName,
                                   names = n.CoName,
                                   code = n.CoCode,
                                   remark = n.CoRemark,
                                   creator = n.CoCreate,
                                   createDate = n.CoCreateTime,
                                   sort = n.CoSort
                               };
                    return data.OrderBy(k => k.sort).ToList();
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        #endregion

        #region 获取系统设置

        public class SystemConfigModel
        {
            public int id { get; set; }
            public string tab { get; set; }
            public string tabName { get; set; }
            public string name { get; set; }
            public string value { get; set; }
            public string info { get; set; }
            public string type { get; set; }
            public string inputType { get; set; }
            public string parameter { get; set; }
            public int sort { get; set; }
            public string language { get; set; }
        }

        /// <summary>
        /// 通过类型获取码表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<SystemConfigModel> GetSystemConfig(string tab = "")
        {
            try
            {
                using (mtContext mtContext = new mtContext())
                {
                    var data = from tabs in mtContext.TbSystemConfigTabs.AsNoTracking().Where(k => k.Status == true)
                               join config in mtContext.TbSystemConfigs.AsNoTracking().Where(k => k.Status == true)
                               on tabs.Id equals config.ConfigTab
                               select new SystemConfigModel
                               {
                                   id = tabs.Id,
                                   tab = tabs.EngTitle,
                                   tabName = tabs.Title,
                                   name = config.MenuName,
                                   value = config.Value,
                                   info = config.Info,
                                   type = config.Type,
                                   inputType = config.InputType,
                                   parameter = config.Parameter,
                                   sort = config.Sort,
                                   language = config.Language
                               };
                    if (!string.IsNullOrEmpty(tab))
                    {
                        data = data.Where(k => k.tab == tab);
                    }
                    return data.OrderBy(k => k.sort).ToList();
                }
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        #endregion
    }
}
